#include "yb_form_qlsjsc.h"
#include "ui_yb_form_qlsjsc.h"
#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QDir>
#include <QSqlError>

Form_qlsjsc::Form_qlsjsc(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_qlsjsc)
{
    ui->setupUi(this);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/qlsjsc").toRect();
    this->setGeometry(rct);

    ui->deDate0->setDate(QDate::currentDate());
    ui->deDate1->setDate(QDate::currentDate());
    ui->deStart->setDate(QDate::currentDate());
    ui->deEnd->setDate(QDate::currentDate());

    ui->rbUn->setVisible(false);
    ui->rbDate->setVisible(false);

    ui->tabWidget->setCurrentIndex(0);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    mdList = new QSqlQueryModel();
    md_store = new QSqlQueryModel();

    //网络参数
    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    open_log_file();

    ui->ckb_upload_batch->setEnabled(false);

}

Form_qlsjsc::~Form_qlsjsc()
{
    delete ui;
}

void Form_qlsjsc::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/qlsjsc", QVariant(this->geometry()));

    emit destroyW( "qlsjsc" );

}

void Form_qlsjsc::open_log_file()
{

    //保留最近5次日志文件
    QString basePath = pub::base_path + "/logs/upload";
    QDir d = QDir(basePath);
    d.setNameFilters( QStringList("*.log") );
    d.setSorting(QDir::Name);   //sorted by name, reversed.
    d.setSorting(QDir::Reversed);
    QStringList files = d.entryList();  //read filenames
qDebug()<<files;
    for(int i = 5; i < files.size() ; i++){
        QFile f(basePath + "/" + files[i]);
            f.remove();
    }

    QString fileName = "logs/upload/" + QDate::currentDate().toString("yyyyMMdd") + ".log";
qDebug()<<fileName;
    logFile =  new QFile(fileName);
}

void Form_qlsjsc::on_pbUpload_clicked()
{
    if(!ui->cb3501->isChecked() && !ui->cb3503->isChecked() && !ui->cb3504->isChecked() &&
            !ui->cb3505->isChecked() && !ui->cb3506->isChecked() )
    {
        QMessageBox::information(this,"注意","未选定有效上传范围！");
        return;
    }

    ui->pbUpload->setEnabled(false);
    qApp->processEvents();

    if(ui->cb3501->isChecked())//盘存
    {
        upload3501();//盘存

    }

    if(ui->cb3503->isChecked())
    {
        upload0304("3503", "01");   //一般入库
        //upload0304("3503", "07");   //特殊入库
        //upload0304("3503", "06");   //
    }
    if(ui->cb3504->isChecked())
    {
        upload0304("3504", "06");   //入库退库
    }
    if(ui->cb3505->isChecked())
    {
        upload0506("3505","M1");   //发药
    }
    if(ui->cb3506->isChecked())
    {
        upload0506("3506","M2");   //退药
    }

    ui->pbUpload->setEnabled(true);
}

void Form_qlsjsc::on_pbExit_clicked()
{
    close();
}

void Form_qlsjsc::on_pbSearch_clicked()
{
    QString condition = " from pha_com_sto_upload up ";

    if(ui->rb3505u->isChecked() || ui->rb3506u->isChecked())
    {
        condition = " , reg.name 患者姓名, reg.card_no 病志号, reg.clinic_code "
                    " from pha_com_sto_upload up "
                    " left join pha_com_output out on out.upload_no = up.fixmedins_bchno "
                    " left join fin_opr_register reg on reg.clinic_code = out.get_person ";
    }


    sq = " select up.fixmedins_bchno 批次号, up.drug_code 编码, up.drug_name 品名,"
         " up.count 数量, to_char(up.oper_date, 'yyyy-mm-dd') 上传日期, up.relate_bchno 关联号"
         " %1 "
         " where up.cancel_flag <> '1' and ";
    sq += " up.oper_date >= to_date('"+ui->deDate0->date().toString("yyyy-MM-dd")+"','yyyy-mm-dd') ";
    sq += " and trunc(up.oper_date) <= to_date('"+ui->deDate1->date().toString("yyyy-MM-dd")+"','yyyy-mm-dd') ";
    sq += " and up.drug_name like '%" + ui->leDrugName->text().trimmed() + "%'  and up.type = ";

    if(ui->rb3501u->isChecked()) { sq += "'3501'";}
    if(ui->rb3502u->isChecked()) { sq += "'3502'";}
    if(ui->rb3503u->isChecked()) { sq += "'3503'";}
    if(ui->rb3504u->isChecked()) { sq += "'3504'";}
    if(ui->rb3505u->isChecked()) { sq += "'3505'";}
    if(ui->rb3506u->isChecked()) { sq += "'3506'";}

    sq += " order by up.fixmedins_bchno";

    sq = sq.arg(condition);

    qDebug()<<"检索已经上传的进销存信息：";
    qDebug()<<sq<<"\n";

    if(!qrot->exec(sq))
    {
        QMessageBox::warning(this, "注意", qrot->lastError().text());
        return;
    }
    if(!qrot->next()){
        QMessageBox::warning(this, "注意", "sql return is empty.");
    }
    mdList->setQuery(sq, pub::db_o);

    ui->tvUploaded->setModel(mdList);

    ui->leBatch->clear();
}

void Form_qlsjsc::on_tvUploaded_clicked(const QModelIndex &index)
{
    ui->leBatch->setText(index.siblingAtColumn(0).data(0).toString());
}

void Form_qlsjsc::on_rb3501u_clicked()
{
    ui->leBatch->clear();
}

void Form_qlsjsc::on_rb3502u_clicked()
{
    ui->leBatch->clear();
}

void Form_qlsjsc::on_rb3503u_clicked()
{
    ui->leBatch->clear();
}

void Form_qlsjsc::on_rb3504u_clicked()
{
    ui->leBatch->clear();
}

void Form_qlsjsc::on_rb3505u_clicked()
{
    ui->leBatch->clear();
}

void Form_qlsjsc::on_rb3506u_clicked()
{
    ui->leBatch->clear();
}

void Form_qlsjsc::on_pbUpload_2_clicked()
{
    if(ui->leBatch->text().isEmpty())
    {
        QMessageBox::warning(this, "注意", "批次流水号为空！");
        return;
    }
    QJsonObject in,inpu;   //医保交易入参信息
    inpu.insert("fixmedins_bchno", ui->leBatch->text());//生产日期	日期型
    //进销存数据类型	字符型	30	Y	Y	1-盘存信息；2-库存变更信息；3-采购信息；4-销售信息

    QString tbName;  //关联表名称
    if(ui->rb3501u->isChecked()) {inpu.insert("inv_data_type","1"); tbName = "pha_com_storage"; }
    if(ui->rb3502u->isChecked()) {inpu.insert("inv_data_type","2");tbName = ""; }
    if(ui->rb3503u->isChecked()) {inpu.insert("inv_data_type","3");tbName = "pha_com_input"; }
    if(ui->rb3504u->isChecked()) {inpu.insert("inv_data_type","3");tbName = "pha_com_input"; }
    if(ui->rb3505u->isChecked()) {inpu.insert("inv_data_type","4");tbName = "pha_com_output"; }
    if(ui->rb3506u->isChecked()) {inpu.insert("inv_data_type","4");tbName = "pha_com_output"; }
    in.insert("data", inpu);

    if(call_noRet("3507",in))
    {
        ui->ptOut_2->appendPlainText("  " + ui->leBatch->text() + " - 3507 已传送。");
        sq = "update pha_com_sto_upload set cancel_flag = '1', cancel_date = sysdate where "
             " fixmedins_bchno = '"+ui->leBatch->text()+"'";
        qrot->exec(sq);

        if(!tbName.isEmpty())
        {
            sq = "update " + tbName;
            sq += " set upload_no = 0 where upload_no = "+ui->leBatch->text();
            qrot->exec(sq);

        }
    }
}

bool Form_qlsjsc::call_noRet(QString busi, QJsonObject &inpu, QString clinic_code)
{
    QJsonObject jsonRet;    //医保交易返回的Json数据
    QString info;   //如果返回错误，保存错误信息

    if( ! pub::call_business(busi, inpu, info, jsonRet, "", true , manager, request, clinic_code))
    {
        QMessageBox::warning(this, "注意", info);
        return false;
    }

    return true;
}

void Form_qlsjsc::upload0304(QString busi, QString intype, bool self_called)
{

    QString dept_type;

    sq = "select a.med_list_codg, a.drug_code, a.trade_name," // 0 - 2
         " a.company_code, a.manu_date,　d.producer_code,"  // 3 - 5
         " d.approve_info, a.batch_no, a.manu_date, "
         "a.valid_date, a.in_num,'1',"  //6 - 11
         " to_char(a.apply_date,'yyyy-mm-dd hh24:mi:ss'), "
         "a.oper_code, " //12 - 13
            " a.in_bill_code, "
            "to_char(a.retail_price/a.pack_qty,'fm99999.999999'), "
            "a.mark, a.invoice_no, "
            " a.group_code, a.drug_dept_code, d.split_type"
            " from pha_com_input a,  pha_com_baseinfo d "
            " where ";
    if(self_called)
    {
        sq += " a.oper_date between to_date('"
                + ui->deStart->date().toString("yyyy-MM-dd")
                + "','yyyy-mm-dd') and to_date('"
                + ui->deEnd->date().toString("yyyy-MM-dd")
                + " 23:59:59','yyyy-mm-dd hh24:mi:ss')";
    }
    else
    {
        sq += " a.oper_date > trunc(sysdate) - 1 ";

    }
    //sq += " and d.trade_name like '%" + ui->leName->text().trimmed()+"%'";
    sq += " and a.manu_date is not null and in_type = '" + intype ;
    sq += "' and a.drug_dept_code "
             " in(select dept_code from com_department where dept_type = 'PI') ";
    sq += " and a.drug_code = d.drug_code";
    sq += " and (a.upload_no = 0 or a.upload_no is null )";


    qDebug()<<"提取入库，退库数据："<<sq;

    if(!qro->exec(sq))
    {
        QMessageBox::information(this,"错误","提取 "+busi+" 数据失败！\n" + qro->lastError().text());
        qDebug()<<"提取 "<<busi<<" 数据失败！\n"<<qro->lastError().text();
        return;
    }
    int recCount = 0;
    QJsonObject in1,inpu1;   //3503,3504医保交易入参信息
    QJsonObject in2,inpu2;   //3502医保交易入参信息
    QString bch_code1,bch_code2;   //批次流水号

    logFile->open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(logFile);

    while(qro->next())
    {
        QString med_list_codg = qro->value(0).toString();
        if(med_list_codg.isEmpty())
        {
            qDebug()<<"pha_com_input has no med_list_codg \n";
            QString dgcd = qro->value("drug_code").toString();
            qrot->exec("select med_list_codg  from fin_com_compare where fixmedins_hilist_id = '"+dgcd+"'");
            qrot->next();
            med_list_codg = qrot->value(0).toString();

            if(med_list_codg.isEmpty())
            {
                qDebug()<<"fin_com_compare has no med_list_codg \n";
                ui->ptOut->appendPlainText("\n" +qro->value(2).toString() + " 关联的 med_list_codg 为空白,请先进行医保药品对照！" );
                text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                        << qro->value(2).toString() + " 关联的 med_list_codg 为空白,请先进行医保药品对照！"  << "\r\n";
                continue;
            }
        }
        //生成批次流水号,3503使用新号，3504使用关联正数据流水号
        if(busi == "3503")
        {
            sq = "select seq_pha_com_upload.nextval from dual";
        }
        else
        {
            sq = "select upload_no from pha_com_input where in_type = '01' ";
            sq += " and drug_dept_code = '" + qro->value(19).toString() + "'";
            sq += " and drug_code = '" + qro->value(1).toString() + "'";
            sq += " and group_code = '" + qro->value(18).toString() + "'";
            sq += " and batch_no = '" + qro->value(7).toString() + "'";
        }
        //qrot->exec("select seq_pha_com_upload.nextval from dual");
        qrot->exec(sq);
        qrot->next();
        bch_code1 = qrot->value(0).toString();
        if(bch_code1.isEmpty())
        {

            ui->ptOut->appendPlainText("\n找不到有效的正数关联记录！\n drug_code is "
                                       + qro->value(1).toString()
                                       + "\n trade_name "
                                       + qro->value(2).toString()
                                       + "\n group_code "
                                       + qro->value(18).toString()
                                       + "\n batch_no "
                                       + qro->value(7).toString()
                                       + "\n oper_date "
                                       + qro->value(12).toString()

                                       );
            text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                        << "\n找不到有效的正数关联记录！\n drug_code is "
                           + qro->value(1).toString()
                           + "\n trade_name "
                           + qro->value(2).toString()
                           + "\n group_code "
                           + qro->value(18).toString()
                           + "\n batch_no "
                           + qro->value(7).toString()
                           + "\n oper_date "
                           + qro->value(12).toString()

                        << "\r\n";
            continue;

        }
        qrot->exec("select seq_pha_com_upload.nextval from dual");
        qrot->next();
        bch_code2 = qrot->value(0).toString();

        QString spler_name,prodentp_name;
        //代码
        spler_name = qro->value(3).toString();
        prodentp_name = qro->value(5).toString();

        //代码转名称
        sq = " select fac_name,fac_code "
             " from pha_com_company "
             " where fac_code in('"+spler_name+"','"+prodentp_name+"')";
        qrot->exec(sq);
        while(qrot->next())
        {
            if(qrot->value("fac_code").toString() == spler_name)
            {
                spler_name = qrot->value("fac_name").toString();
            }
            if(qrot->value("fac_code").toString() == prodentp_name)
            {
                prodentp_name = qrot->value("fac_name").toString();
            }
        }

        inpu1.insert("med_list_codg", med_list_codg);//医疗目录编码	字符型	50  qro->value(0).toString()
        inpu1.insert("fixmedins_hilist_id", qro->value(1).toString());//定点医药机构目录编号	字符型	30
        inpu1.insert("fixmedins_hilist_name", qro->value(2).toString());//定点医药机构目录名称	字符型	200
        inpu1.insert("rx_flag", qro->value(11).toString());//处方药标志	字符型	3
        inpu1.insert("spler_name", spler_name);//供应商名称	字符型	200	　	Y
        inpu1.insert("manu_lotnum", qro->value(7).toString());//生产批号	字符型	30
        inpu1.insert("prodentp_name", prodentp_name);//生产厂家名称	字符型	200	　	Y
        inpu1.insert("aprvno", qro->value(6).toString());//批准文号	字符型	100
        inpu1.insert("fixmedins_bchno", bch_code1);//定点医药机构批次流水号	字符型	30
        inpu1.insert("manu_date", qro->value(8).toDate().toString("yyyy-MM-dd"));//生产日期	日期型
        inpu1.insert("expy_end", qro->value(9).toDate().toString("yyyy-MM-dd"));//有效期止	日期型
        inpu1.insert("purc_retn_cnt", qro->value(10).toString());//采购/退货数量	数值型	16,4	　	Y
        inpu1.insert("purc_retn_stoin_time", qro->value(12).toString());//采购/退货入库时间
        inpu1.insert("purc_retn_opter_name", qro->value(13).toString());//采购/退货经办人姓名	字符型
        inpu1.insert("in_bill_code", qro->value(14).toString());//入库唯一记录号
        inpu1.insert("purchase_price", qro->value(15).toString());//价格
        QString t = qro->value(16).toString();
        inpu1.insert("purc_invo_codg", t.isEmpty() ? "-" : t );//发票代码
        t = qro->value(17).toString();
        inpu1.insert("purc_invo_no", t.isEmpty() ? "-" : t );//发票号

        in1.insert("purcinfo",inpu1);

        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " "<<busi<<" : "<<QJsonDocument(in1).toJson() << "\r\n";

        if(call_noRet(busi,in1))
        {
            recCount++;
            ui->ptOut->appendPlainText(qro->value(12).toString()
                                       + " - " + qro->value(2).toString() + " - "+busi+" 已传送。");

            sq = "insert into pha_com_sto_upload "
                 "(fixmedins_bchno,relate_bchno,oper_date,drug_code,"
                 "drug_name,count,type) "
                 "values(";
            sq += "'" + bch_code1 + "','" + bch_code2 + "', sysdate, '";
            sq += inpu1["fixmedins_hilist_id"].toString() + "','";
            sq += inpu1["fixmedins_hilist_name"].toString() + "',";
            sq += inpu1["purc_retn_cnt"].toString() + ",'"+busi+"')";
            qrot->exec(sq);

            sq = "update pha_com_input set upload_no = "+bch_code1+" where in_bill_code = '";
            sq += inpu1["in_bill_code"].toString() +"' ";
            qrot->exec(sq);
        }
        else
        {
            if(ui->rb_err_return->isChecked())
            {
                break;
            }
            else
            {
                if(qro->next())
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }

        if(ui->ckb_no3502->isChecked())
        {
            //特殊操作，不进行库存变更
            if(qro->next())
            {
                continue;
            }
            else
            {
                break;
            }
        }

        inpu2.insert("med_list_codg", med_list_codg);//医疗目录编码	字符型	50  qro->value(0).toString()
        inpu2.insert("fixmedins_hilist_id", qro->value(1).toString());//定点医药机构目录编号	字符型	30
        inpu2.insert("fixmedins_hilist_name", qro->value(2).toString());//定点医药机构目录名称	字符型	200
        inpu2.insert("fixmedins_bchno", bch_code2);//定点医药机构批次流水号	字符型	30
        inpu2.insert("rx_flag", qro->value(11).toString());//处方药标志	字符型	3
        inpu2.insert("cnt", inpu1["purc_retn_cnt"].toString());//变更数量	数值型	16,2
        inpu2.insert("pric", inpu1["purchase_price"].toString());//单价	数值型	16,6
        inpu2.insert("inv_chg_opter_name", pub::usr_code);//库存变更经办人姓名	字符型	50
        inpu2.insert("inv_chg_type", "106");//库存变更类型	字符型	106 ,
        inpu2.insert("inv_chg_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//库存变更时间
        inpu2.insert("memo", "");//备注	字符型	500

        QString split = qro->value("split_type").toString();
        if(split == "0")
        {
            inpu2.insert("trdn_flag", "1");//	拆零标志	字符型	2
        }
        else
        {
            inpu2.insert("trdn_flag", "0");//	拆零标志	字符型	2
        }
        //inpu2.insert("trdn_flag", "");//	拆零标志	字符型	2

        in2.insert("invinfo",inpu2);

        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 3502 : "<<QJsonDocument(in2).toJson() << "\r\n";

        if(call_noRet("3502",in2))
        {
            ui->ptOut->appendPlainText("  " + qro->value(2).toString() + " - 3502 已传送。");
            sq = "insert into pha_com_sto_upload "
                 "(fixmedins_bchno, relate_bchno, oper_date, drug_code, drug_name, count, type) "
                 "values(";
            sq += "'" + bch_code2 + "','" + bch_code1 + "', sysdate, '";
            sq += inpu2["fixmedins_hilist_id"].toString() + "','";
            sq += inpu2["fixmedins_hilist_name"].toString() + "',";
            sq += inpu2["cnt"].toString() + ",'3502')";
            qrot->exec(sq);
        }
        else
        {
            if(ui->rb_err_return->isChecked())
            {
                break;
            }
            else
            {
                if(qro->next())
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
    }
    ui->ptOut->appendPlainText("\n" +busi + " 共处理数据 " + QString::number(recCount) + " 条。");
    logFile->flush();
    logFile->close();

}

void Form_qlsjsc::upload0506(QString busi, QString outtype, QString reci_no)
{

    sq = "select b.med_list_codg, a.drug_code,  a.trade_name, " //0-2
         " h.doct_code, a.oper_code, " //医师姓名，药师姓名 待生成 json 时查询。 3-4
         " a.oper_code, '-', h.paykind_code, 'c.setl_id', 'c.mdtrt_id', a.batch_no,"// 5 - 10
         " CASE WHEN a.manu_date is null THEN"
         "     (select to_char(manu_date,'yyyy-mm-dd') "
         "     from pha_com_storage e "
         "     where rownum = 1 and e.drug_code = a.drug_code "
         "     and e.group_code = a.group_code and a.batch_no = e.batch_no) "
         "     ELSE to_char(a.manu_date,'yyyy-mm-dd') END," //11
         " to_char(a.valid_date,'yyyy-mm-dd'), '1', '0', h.invoice_no, a.out_num," //12-16
         " to_char(a.apply_date, 'yyyy-mm-dd hh24:mi:ss'), a.oper_code, " //17-18
         "  a.out_bill_code, to_char(a.retail_price/a.pack_qty,'fm99999.999999'), "//19-20
         " a.get_person, a.group_code, a.recipe_no, base.split_type, "//21-24
         " (a.out_num / a.pack_qty) package_num"//25,包装数量,为计算应上传追溯码数量
         " from "
         " pha_com_output a , "
         " fin_com_compare b , "
         " PHA_STO_RECIPE h ,"
         " pha_com_baseinfo base "
         " where ";
    if(reci_no.isEmpty())
    {
        sq += " a.oper_date between to_date('"
                + ui->deStart->date().toString("yyyy-MM-dd")
                + "','yyyy-mm-dd') and to_date('"
                + ui->deEnd->date().toString("yyyy-MM-dd")
                + " 23:59:59','yyyy-mm-dd hh24:mi:ss')" ;
                  //" and b.center_name like '%"
                //+ ui->leName->text().trimmed() + "%'" ;
    }
    else
    {
        sq += " a.recipe_no = '" + reci_no + "'";
    }
    sq += " and out_type = '" + outtype + "' ";
    sq += " and b.fixmedins_hilist_id = a.drug_code "
          " and base.drug_code = a.drug_code "
          " and h.recipe_no = a.recipe_no ";

    sq += " and (a.upload_no = 0 or a.upload_no is null )";


    qDebug()<<busi<<" 提取数据："<<sq;

    if(!qro->exec(sq))
    {
        QMessageBox::information(this,"错误","提取 "+busi+" 数据失败！");
        qDebug()<<"提取 "<<busi<<" 数据失败！\n"<<qro->lastError().text();
        return;
    }

    if(!qro->next())
    {
        ui->ptOut->appendPlainText("指定范围的 "+busi+" 数据为空！");
        return;
    }

    qro->last();
    int record_count = qro->at() + 1;
    qro->first();

    QJsonArray in_0506_all, in_02_all;   //批量上传

    QString sq_all_0506, sq_all_02;  //批量上传
    QStringList update_sqls;

    int recCount = 0;
    QJsonDocument jsdc; //用于清除 QJsonObject
    QJsonObject in1,inpu1;   //3505,3506医保交易入参信息
    QJsonObject in2,inpu2;   //3502医保交易入参信息

    QJsonObject trace;  //3505,3506用到的追溯码
    QString bch_code1,bch_code2;   //批次流水号

    logFile->open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(logFile);

    QString cur_clinic_code ;

    while(true)
    {
        QJsonArray trace_list;  //3505,3506用到的追溯码
        inpu1 = jsdc.object();  // inpu1 医保和现金项目不同，清除以防止不必要的数据干扰
        trace = jsdc.object();  // 清除

        cur_clinic_code = qro->value(21).toString();//	clinic_code

        QString med_list_codg = qro->value(0).toString();

        if(med_list_codg.isEmpty())
        {
            qDebug()<<"pha_com_output has no med_list_codg \n";
            QString dgcd = qro->value("drug_code").toString();
            qrot->exec("select med_list_codg  from fin_com_compare where fixmedins_hilist_id = '"+dgcd+"'");
            qrot->next();
            med_list_codg = qrot->value(0).toString();

            if(med_list_codg.isEmpty())
            {
                qDebug()<<"fin_com_compare has no med_list_codg \n";
                ui->ptOut->appendPlainText("\n" +qro->value(2).toString() + " 关联的 med_list_codg 为空白,请先进行医保药品对照！" );

                if(qro->next())
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }

        //查询是否存在追溯码
        sq = "select bar_code from pha_sto_barcode_rec "
             " where recipe_no = '" + qro->value("recipe_no").toString() + "'";
        sq += " and drug_code = '" + qro->value("drug_code").toString() + "'";
        sq += " and upload_no = 0 ";//未上传过的追溯码

        //跨批号时，同一项目会出现超过一次，需要按项目数量提取追溯码数量
        sq += " and rownum <= " + qro->value("package_num").toString();

        if(busi == "3505")
        {
            sq += " and bar_code_count > 0 ";
        }
        else
        {
            sq += " and bar_code_count < 0 ";
        }

        qDebug()<<"查询是否存在追溯码: "<<sq;
        QStringList trace_code_lst ;
        qrot->exec(sq);
        while(qrot->next())
        {
            QString code = qrot->value(0).toString();
            if(code.length() == 20)
            {
                trace_code_lst << code;//保存追溯码，为标记 pha_sto_barcode_rec 表中的追溯码使用状态

                trace.insert("drug_trac_codg", code); //为3505、3506交易准备参数
                trace_list << trace;

            }
        }

        //生成批次流水号, 3505使用新流水号，3506使用对应正数据的流水号
        if(busi == "3505")
        {
            sq = "select seq_pha_com_upload.nextval from dual";
        }
        else
        {
            sq = "select upload_no from pha_com_output where out_type = 'M1' ";
            sq += " and recipe_no = '" + qro->value(23).toString() + "'";
            sq += " and drug_code = '" + qro->value(1).toString() + "'";
            sq += " and group_code = '" + qro->value(22).toString() + "'";
        }

        qrot->exec(sq);
        qrot->next();
        bch_code1 = qrot->value(0).toString();  //3505,3506使用

        if(bch_code1.isEmpty())
        {
            ui->ptOut->appendPlainText("\n找不到有效的正数关联记录！"
                                       "\n recipe_code is "
                                       +qro->value(23).toString()
                                       + "\n drug_code is "
                                       +qro->value(1).toString()
                                       + "\n trade_name is "
                                       +qro->value(2).toString()

                                       );
            text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                        << " 找不到有效的正数关联记录！\n recipe_code is "
                           +qro->value(23).toString()
                           + "\n drug_code is "
                           +qro->value(1).toString()
                           + "\n trade_name is "
                           +qro->value(2).toString()

                        << "\r\n";

            if(qro->next())
            {
                continue;
            }
            else
            {
                break;
            }
        }
        qrot->exec("select seq_pha_com_upload.nextval from dual");
        qrot->next();
        bch_code2 = qrot->value(0).toString(); //3502使用

        inpu1.insert("med_list_codg", med_list_codg);//	医疗目录编码	字符型
        inpu1.insert("fixmedins_hilist_id", qro->value(1).toString());//	定点医药机构目录编号	字符型
        inpu1.insert("fixmedins_hilist_name", qro->value(2).toString());//	定点医药机构目录名称	字符型
        inpu1.insert("fixmedins_bchno", bch_code1);//	定点医药机构批次流水号	字符型
        qrm->exec("select empl_name from com_employee where empl_code = '"
                  + qro->value(3).toString() + "' limit 1") ;
        qrm->next();
        inpu1.insert("prsc_dr_name", qrm->value(0).toString());//	开方医师姓名	字符型
        qrm->exec("select empl_name from com_employee where empl_code = '"
                  + qro->value(4).toString() + "' limit 1") ;
        qrm->next();
        inpu1.insert("phar_name", qrm->value(0).toString());//	药师姓名	字符型
        inpu1.insert("phar_prac_cert_no", qro->value(5).toString());//	药师执业资格证号	字符型

        //预设值为现金结算
        inpu1.insert("hi_feesetl_type", "0");//	医保费用结算类型	字符型
        inpu1.insert("mdtrt_sn", cur_clinic_code);//	就医流水号 clinic_code
        inpu1.insert("mdtrt_setl_type", "2");//	就诊结算类型	1-医保结算2-自费结算

        inpu1.insert("manu_lotnum", qro->value(10).toString());//	生产批号	字符型
        inpu1.insert("manu_date", qro->value(11).toString());//	生产日期	日期型
        inpu1.insert("expy_end", qro->value(12).toString());//	有效期止	日期型
        inpu1.insert("rx_flag", qro->value(13).toString());//	处方药标志	字符型

        QString split = qro->value("split_type").toString();
        if(split == "0")
        {
            inpu1.insert("trdn_flag", "1");//	拆零标志	字符型	2
        }
        else
        {
            inpu1.insert("trdn_flag", "0");//	拆零标志	字符型	2
        }

        //20250705修改
        //inpu1.insert("rtal_docno", qro->value(15).toString());//	零售单据号	字符型
        //
        //通过处方号和项目代码提取费用明细流水号。同一处方号下不应该出现相同项目代码
        QString tmpsq = "select mo_order from fin_opb_feedetail "
                        " where recipe_no = '"+qro->value(23).toString()+"'"
                        " and item_code = '"+qro->value(1).toString()+"'";
        qrot->exec(tmpsq);
        qDebug()<<"通过处方号和项目代码提取费用明细流水号";
        qDebug()<<tmpsq;

        QString mo_order = "";

        if(!qrot->next())
        {
            qDebug()<<"按指定处方号和项目代码找不到费用流水号";

            ui->ptOut->appendPlainText("\n按指定处方号和项目代码找不到费用流水号");

            if(ui->rb_err_return->isChecked())
            {
                break;
            }
            else
            {
                if(qro->next())
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }

        mo_order = qrot->value(0).toString();
        inpu1.insert("rtal_docno", mo_order);

        //--20250705修改

        if(qro->value(7).toString() == "02")   //医保
        {
            //医保挂号，不一定使用医保结算
            //使用医保结算，不一定全部项目都是医保结算

            qrot->exec("select clinic_code from fin_opb_insu_cash "
                       " where mo_order = '" + mo_order + "'");
            if(qrot->next())
            {
                //fin_opb_insu_cash表中存在 mo_order 为医保超限量强制以现金模式开出的药品，不按医保上传
            }
            else
            {
                qrot->exec("select setl_id, mdtrt_id mdtrt_sn, psn_no,idenno certno,name psn_name"
                           " from fin_ipr_siinmaininfo d where d.invoice_no = '" + qro->value(15).toString() + "'");
                if(qrot->next())
                {
                    //医保挂号且医保结算，按医保上传
                    inpu1.insert("hi_feesetl_type", "1");//	医保费用结算类型	字符型
                    inpu1.insert("setl_id", qrot->value("setl_id").toString());//	结算ID	字符型
                    inpu1.insert("mdtrt_sn", qrot->value("mdtrt_sn").toString());//	就医流水号
                    inpu1.insert("psn_no", qrot->value("psn_no").toString());  //人员编号
                    inpu1.insert("psn_cert_type", "01");  //人员证件类型, 01 身份证
                    inpu1.insert("certno", qrot->value("certno").toString());  //证件号码
                    inpu1.insert("psn_name", qrot->value("psn_name").toString());  //人员姓名
                    inpu1.insert("mdtrt_setl_type", "1");//	就诊结算类型	1-医保结算2-自费结算
                }
            }
        }


        // out_bill_code ，医保交易不使用， 本地数据操作需要用
        inpu1.insert("out_bill_code", qro->value(19).toString());//	output unique serial number

        inpu1.insert("sel_retn_cnt", qro->value(16).toString());//	销售/退货数量	数值型
        inpu1.insert("sel_retn_time", qro->value(17).toString());//	销售/退货时间	日期时间型
        inpu1.insert("sel_retn_opter_name", qro->value(18).toString());//	销售/退货经办人姓名	字符型
        inpu1.insert("purchase_price", qro->value(20).toString());//

        inpu1.insert("drugtracinfo", trace_list);   //追溯码

        in1.insert("selinfo",inpu1);
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " "<<busi<<" : " << QJsonDocument(in1).toJson()<<"\r\n";

        if(ui->ckb_upload_batch->isChecked())
        {
            in_0506_all << inpu1;
            QString tmp = "('" + bch_code1 + "','" + bch_code2 + "', sysdate, '";
                    tmp += inpu1["fixmedins_hilist_id"].toString() + "','";
                    tmp += inpu1["fixmedins_hilist_name"].toString() + "',";
                    tmp += inpu1["sel_retn_cnt"].toString() + ",'"+busi+"A')";
            if(sq_all_0506.isEmpty())
            {
                sq_all_0506.append(tmp);
            }
            else
            {
                sq_all_0506.append(" , " + tmp);
            }

            tmp = "update pha_com_output set upload_no = "+bch_code1;
            tmp += " where out_bill_code = '" + inpu1["out_bill_code"].toString() +"' ";
            update_sqls << tmp;
        }
        else
        {

            if(call_noRet(busi, in1, cur_clinic_code))
            {
                recCount++;
                ui->ptOut->appendPlainText(qro->value(17).toString()
                                           + " - " + qro->value(2).toString() + " - "+busi+" 已传送。");

                sq = "insert into pha_com_sto_upload "
                     "(fixmedins_bchno, relate_bchno, oper_date, drug_code, drug_name, count, type) "
                     "values(";
                sq += "'" + bch_code1 + "','" + bch_code2 + "', sysdate, '";
                sq += inpu1["fixmedins_hilist_id"].toString() + "','";
                sq += inpu1["fixmedins_hilist_name"].toString() + "',";
                sq += inpu1["sel_retn_cnt"].toString() + ",'"+busi+"')";
                qrot->exec(sq);
                sq = "update pha_com_output set upload_no = "+bch_code1+" where out_bill_code = '";
                sq += inpu1["out_bill_code"].toString() +"' ";
                qrot->exec(sq);

                //追溯码使用状态保存
                if(trace_code_lst.size() > 0)
                {
                    sq = "update pha_sto_barcode_rec "
                         " set upload_no = '%1' "
                         " where bar_code in('%2')";
                    sq = sq.arg(bch_code1).arg(trace_code_lst.join("','"));

                    qDebug()<<"保存追溯码使用状态："<<sq<<"\n";
                    qrot->exec(sq);

                }

            }
            else
            {
                //
                if(ui->rb_err_return->isChecked())
                {
                    break;
                }
                else
                {
                    if(qro->next())
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        if(ui->ckb_no3502->isChecked())
        {
            //特殊操作，不进行库存变更
            if(qro->next())
            {
                continue;
            }
            else
            {
                break;
            }
        }

        inpu2.insert("med_list_codg", med_list_codg);//医疗目录编码	字符型	50
        inpu2.insert("fixmedins_hilist_id", qro->value(1).toString());//定点医药机构目录编号	字符型	30
        inpu2.insert("fixmedins_hilist_name", qro->value(2).toString());//定点医药机构目录名称	字符型	200
        inpu2.insert("fixmedins_bchno", bch_code2);//定点医药机构批次流水号	字符型	30
        inpu2.insert("rx_flag", qro->value(13).toString());//处方药标志	字符型	3
        inpu2.insert("cnt", inpu1["sel_retn_cnt"].toString());//变更数量	数值型	16,2
        inpu2.insert("pric", inpu1["purchase_price"].toString());//单价	数值型	16,6
        inpu2.insert("inv_chg_opter_name", pub::usr_code);//库存变更经办人姓名	字符型	50
        inpu2.insert("inv_chg_type", "107");//库存变更类型	字符型	106 ,
        inpu2.insert("inv_chg_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//库存变更时间
        inpu2.insert("memo", "");//备注	字符型	500

        split = qro->value("split_type").toString();

        if(split == "0")
        {
            inpu2.insert("trdn_flag", "1");//	拆零标志	字符型	2
        }
        else
        {
            inpu2.insert("trdn_flag", "0");//	拆零标志	字符型	2
        }
        //inpu2.insert("trdn_flag", "");//	拆零标志	字符型	2

        in2.insert("invinfo",inpu2);
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " "<<busi<<" : " <<QJsonDocument(in2).toJson()<<"\r\n";

        if(ui->ckb_upload_batch->isChecked())
        {
            in_02_all << inpu2;
            QString tmp = "('" + bch_code2 + "','" + bch_code1 + "', sysdate, '";
                    tmp += inpu2["fixmedins_hilist_id"].toString() + "','";
                    tmp += inpu2["fixmedins_hilist_name"].toString() + "',";
                    tmp += inpu2["cnt"].toString() + ",'3502A')";
            if(sq_all_02.isEmpty())
            {
                sq_all_02.append(tmp);
            }
            else
            {
                sq_all_02.append(" , " + tmp);
            }
        }
        else
        {

            if(call_noRet("3502", in2, cur_clinic_code))
            {
                ui->ptOut->appendPlainText("  " + qro->value(2).toString() + " - 3502 已传送。");
                sq = "insert into pha_com_sto_upload "
                     "(fixmedins_bchno,relate_bchno,oper_date,drug_code,drug_name,count,type) "
                     "values(";
                sq += "'" + bch_code2 + "','" + bch_code1 + "', sysdate, '";
                sq += inpu2["fixmedins_hilist_id"].toString() + "','";
                sq += inpu2["fixmedins_hilist_name"].toString() + "',";
                sq += inpu2["cnt"].toString() + ",'3502')";
                qrot->exec(sq);
            }
            else
            {
                if(ui->rb_err_return->isChecked())
                {
                    break;
                }
                else
                {
                    if(qro->next())
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        if(!qro->next())
        {
            break;
        }
    }

    if(ui->ckb_upload_batch->isChecked())
    {
        //批量上传
        QJsonObject jsonRet;    //医保交易返回的Json数据
        QString info;   //如果返回错误，保存错误信息

        in1 = jsdc.object();
        in1.insert("selinfoDetail",in_0506_all);

        if( ! pub::call_business(busi + "A", in1, info, jsonRet, "", true , manager, request))
        {
            ui->ptOut->appendPlainText( info);//busi + "A " +
            return ;
        }
        else
        {
            QJsonObject ret_js = jsonRet.value("output").toObject().value("result").toObject();
            QString ret_str = ret_js.value("msgRslt").toString();

            ui->ptOut->appendPlainText("  批量 - " + busi + "A 已传送记录 " + QString::number(record_count) + " 条。");
            ui->ptOut->appendPlainText(ret_str);

            sq = "insert into pha_com_sto_upload "
                 "(fixmedins_bchno,relate_bchno,oper_date,drug_code,drug_name,count,type) "
                 "values";
            sq += sq_all_0506;
            qDebug()<<"批量插入 3505/3506 pha_com_sto_upload ："<<sq;

            qrot->exec(sq);

            qDebug()<<"批量更新 pha_com_output ："<<update_sqls;
            foreach(sq, update_sqls)
            {
                qrot->exec(sq);
            }

        }

        in2 = jsdc.object();
        in2.insert("invinfoDetail",in_02_all);

        jsonRet = jsdc.object();

        if( ! pub::call_business("3502A", in2, info, jsonRet, "", true , manager, request))
        {
            ui->ptOut->appendPlainText( info);//"3502A " +
            return ;
        }
        else
        {
            QJsonArray ret_ar = jsonRet.value("output").toObject().value("invinfoErrDetail").toArray();
            QJsonObject ret_js;
            QString ret_str;

            int ar_size = ret_ar.size();
            while(ar_size > 0)
            {
                ar_size -- ;
                ret_js = ret_ar[ar_size].toObject();
                ret_str.append(ret_js.value("retRslt").toString());
                ret_str.append(" , ");
                ret_str.append(ret_js.value("med_list_codg").toString());
                ret_str.append(" , ");
                ret_str.append(ret_js.value("fixmedins_hilist_name").toString());
                ret_str.append(" , ");
                ret_str.append(ret_js.value("fixmedins_bchno").toString());
                ret_str.append(" , ");
                ret_str.append(ret_js.value("msgRslt").toString());
                ret_str.append("\n");
            }

            ui->ptOut->appendPlainText("  批量 - 3502A 已传送记录 " + QString::number(record_count) + " 条。");
            ui->ptOut->appendPlainText(ret_str);
            sq = "insert into pha_com_sto_upload "
                 "(fixmedins_bchno,relate_bchno,oper_date,drug_code,drug_name,count,type) "
                 "values";
            sq += sq_all_02;
            qDebug()<<"批量插入 3502 pha_com_sto_upload ："<<sq;
            qrot->exec(sq);
        }

    }
    else
    {
        ui->ptOut->appendPlainText("\n" +busi + " 共处理数据 " + QString::number(recCount) + " 条。");
    }

    logFile->flush();
    logFile->close();
}

void Form_qlsjsc::on_pbAllSelect_clicked()
{
    if(ui->cb3503->isChecked()){
        ui->cb3503->setChecked(false);
        ui->cb3504->setChecked(false);
        ui->cb3505->setChecked(false);
        ui->cb3506->setChecked(false);
    }else{
        ui->cb3503->setChecked(true);
        ui->cb3504->setChecked(true);
        ui->cb3505->setChecked(true);
        ui->cb3506->setChecked(true);
    }
}

void Form_qlsjsc::on_pb_fresh_local_clicked()
{
    sq = " select comp.center_name 药品名称, comp.his_specs 规格, "
         " comp.med_list_codg 医保码, comp.fixmedins_hilist_id 本地码,"
         " sum(sto.store_sum/STO.PACK_QTY) 数量,STO.PACK_QTY"
         " from pha_com_stockinfo sto  ,fin_com_compare comp ";
    sq += " where comp.his_name like '%" + ui->le_key_local->text().trimmed()+"%'";
    sq += " and sto.drug_code = comp.fixmedins_hilist_id ";
    sq += " group by comp.med_list_codg, comp.fixmedins_hilist_id,"
          " comp.center_name,comp.his_specs,STO.PACK_QTY";

    if(ui->rb_no_0->isChecked())
    {
        sq += " having sum(sto.store_sum/STO.PACK_QTY) <> 0 ";
    }
    else
    {
        sq += " having sum(sto.store_sum/STO.PACK_QTY) = 0 ";
    }

    sq += " order by center_name ";

    qDebug()<<"提取库存数据 : "<<sq;

    md_store->setQuery(sq, pub::db_o);
    ui->tv_store->setModel(md_store);
    int width = ui->tv_store->width();
    pub::setColumnWidth(ui->tv_store, "0.25^0.15^0.25^0.15^0.1^0^0", width);


}

void Form_qlsjsc::on_tv_store_clicked(const QModelIndex &index)
{
    ui->le_drug_name->setText(index.siblingAtColumn(0).data().toString());
    ui->le_center_code->setText(index.siblingAtColumn(2).data().toString());
    ui->le_his_code->setText(index.siblingAtColumn(3).data().toString());
}

void Form_qlsjsc::on_tv_store_doubleClicked(const QModelIndex &index)
{
    on_tv_store_clicked(index);
}

void Form_qlsjsc::on_pb_check_clicked()
{

    ui->tb_result->clear();

    if(ui->rb_single_item->isChecked())
    {
        if(ui->le_center_code->text().isEmpty())
        {
            QMessageBox::information(this, "注意" , "未指定药品编码！");
            return;
        }

        chk_result_diaplay(ui->le_center_code->text(), ui->le_his_code->text());
    }
    else
    {
        for(int i = 0; i < md_store->rowCount(); i++)
        {
            QModelIndex index = md_store->index( i , 2 );
            QVariant data = md_store->data(index);
            QString center_code = data.toString();

            index = md_store->index( i , 3 );
            data = md_store->data(index);
            QString his_code = data.toString();

            chk_result_diaplay(center_code, his_code);
        }
    }

    ui->tb_result->append("\n数据核对完成\n");

}

void Form_qlsjsc::chk_result_diaplay( QString center_code, QString his_code )
{

    QJsonObject jsonRet;    //医保交易返回的Json数据
    QString info;   //如果返回错误，保存错误信息

    QJsonObject input,data; //入参
    data.insert("med_list_codg", center_code);
    input.insert("data", data);

    if( ! pub::call_business("3561", input, info, jsonRet, "", true , manager, request))
    {
        QMessageBox::warning(this, "注意", info);
        return;
    }

    QJsonArray jsar = jsonRet.value("output").toObject().value("result").toArray();

    if(jsar.size() < 1)
    {
        QString tmp = "医保中心找不到编码为 " + center_code + " 的记录。\n\n";

        ui->tb_result->append(tmp);

        return;
    }

    QJsonArray::iterator it = jsar.begin();

    while(it != jsar.end()){

        QJsonObject jsob = it->toObject();

        QString med_list_codg = jsob.value("med_list_codg").toString();//	医疗目录编码
        QString fixmedins_hilist_id = jsob.value("fixmedins_hilist_id").toString();//	定点医药机构目录编号
        QString fixmedins_hilist_name = jsob.value("fixmedins_hilist_name").toString();//	定点医药机构目录名称
        QString fixmedins_bchno = jsob.value("fixmedins_bchno").toString();//	定点医药机构批次流水号
        int sum_center = jsob.value("cnt").toInt();//	数量

        sq = " select  sum(sto.store_sum) , sto.pack_qty "
             " from pha_com_stockinfo sto  "
             " where sto.drug_code = '" + his_code + "' group by sto.pack_qty";
        qDebug()<<"查询本地数量："<<sq;
        qro->exec(sq);
        qro->next();

        int sum_local = qro->value(0).toInt();
        int pack_qty = qro->value(1).toInt();

        if(ui->rb_single_item->isChecked())
        {

            QString tmp = "定点医药机构目录名称 : " + fixmedins_hilist_name + "\n";
            tmp += "定点医药机构目录编号 : " + fixmedins_hilist_id + "\n";
            tmp += "医保中心医疗目录编码 : " + med_list_codg + "\n";
            tmp += "定点医药机构批次流水号 : " + fixmedins_bchno + "\n";
            tmp += "医保数量 : " + QString::number(sum_center / pack_qty);
            tmp += " , 本地数量 : " + QString::number(sum_local / pack_qty);
            tmp += "\n\n";

            ui->tb_result->append(tmp);
        }
        else
        {
            if(sum_local == sum_center)
            {
                if(!ui->ckb_display_mode->isChecked())
                {
                    QString tmp = "定点医药机构目录名称 : " + fixmedins_hilist_name + "\n";
                    tmp += "定点医药机构目录编号 : " + fixmedins_hilist_id + "\n";
                    tmp += "医保数量与本地数量相等。 \n\n";

                    ui->tb_result->append(tmp);
                }
            }
            else
            {
                QString tmp = "定点医药机构目录名称 : " + fixmedins_hilist_name + "\n";
                tmp += "定点医药机构目录编号 : " + fixmedins_hilist_id + "\n";
                tmp += "医保中心医疗目录编码 : " + med_list_codg + "\n";
                tmp += "定点医药机构批次流水号 : " + fixmedins_bchno + "\n";
                tmp += "医保数量 : " + QString::number(sum_center / pack_qty);
                tmp += " , 本地数量 : " + QString::number(sum_local / pack_qty);
                tmp += "\n\n";

                ui->tb_result->append(tmp);
            }
        }
        it ++ ;
    }

}

void Form_qlsjsc::upload3501()
{

    //提取库存非零且医保对照过的数据

    sq = "select b.med_list_codg, max(a.drug_code), "
         "max(b.center_name), '1',sysdate, sum(a.store_sum), ";
    sq += "'batch_no', 'group_code',";
    sq += " sysdate + 365 , sysdate - 180, "
          "max(to_char(a.retail_price / a.pack_qty,'fm999999.999999')),"
          " max(c.split_type) ";
    sq += " from pha_com_stockinfo a, fin_com_compare b , pha_com_baseinfo c";
    sq +=" where b.his_name like '%" + ui->leName->text().trimmed()+"%'";
    sq += "  and a.drug_code = b.fixmedins_hilist_id "
          " and a.drug_code = c.drug_code "; //and a.store_sum > 0
    if(!ui->rbStoreAll->isChecked()) {
        sq += " and (a.upload_no = 0 or a.upload_no is null) ";
    }
    sq += " group by b.med_list_codg";

    qDebug()<<"提取库存非零且医保对照过的数据,3501 : "<<sq;

    if(!qro->exec(sq))
    {
        QMessageBox::information(this,"错误","提取3501数据失败！\n" + qro->lastError().text());
        qDebug()<<"提取3501数据失败！"<<qro->lastError().text();
        ui->pbUpload->setEnabled(true);
        return;
    }

    int recCount = 0;
    QJsonObject in1,inpu1;   //3501医保交易入参信息
    QJsonObject in2,inpu2;   //3502医保交易入参信息
    QString bch_code1,bch_code2;   //批次流水号


    logFile->open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(logFile);

    while(qro->next())
    {
        //生成批次流水号
        qrot->exec("select seq_pha_com_upload.nextval from dual");
        qrot->next();
        bch_code1 = qrot->value(0).toString();
        qrot->exec("select seq_pha_com_upload.nextval from dual");
        qrot->next();
        bch_code2 = qrot->value(0).toString();

        inpu1.insert("med_list_codg", qro->value(0).toString());//医疗目录编码	字符型	50
        inpu1.insert("fixmedins_hilist_id", qro->value(1).toString());//定点医药机构目录编号	字符型	30
        inpu1.insert("fixmedins_hilist_name", qro->value(2).toString());//定点医药机构目录名称	字符型	200
        inpu1.insert("rx_flag", qro->value(3).toString());//处方药标志	字符型	3
        inpu1.insert("invdate", QDate::currentDate().toString("yyyy-MM-dd"));//盘存日期	日期型
        inpu1.insert("inv_cnt", qro->value(5).toString());//库存数量	数值型	16,2
        inpu1.insert("manu_lotnum", qro->value(6).toString());//生产批号	字符型	30
        //inpu1.insert("groups", qro->value(7).toString());//库存药品批次号	字符型	30
        inpu1.insert("fixmedins_bchno", bch_code1);//定点医药机构批次流水号	字符型	30
        inpu1.insert("manu_date", qro->value(9).toDate().toString("yyyy-MM-dd"));//生产日期	日期型
        inpu1.insert("expy_end", qro->value(8).toDate().toString("yyyy-MM-dd"));//有效期止	日期型
        inpu1.insert("memo", "");//备注	字符型	500

        in1.insert("invinfo",inpu1);

        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 3501 : "<<QJsonDocument(in1).toJson() << "\r\n";

        if(call_noRet("3501",in1))
        {
            recCount++;
            ui->ptOut->appendPlainText(qro->value(2).toString() + " - 3501 已传送。");
            //ui->ptOut->appendPlainText(Qt::DownArrow);
            //ui->ptOut->scroll(0,20);
            sq = "insert into pha_com_sto_upload "
                 "(fixmedins_bchno,relate_bchno,oper_date,drug_code,drug_name,count,type) "
                 "values(";
            sq += "'" + bch_code1 + "','" + bch_code2 + "', sysdate, '";
            sq += inpu1["fixmedins_hilist_id"].toString() + "','";
            sq += inpu1["fixmedins_hilist_name"].toString() + "',";
            sq += inpu1["inv_cnt"].toString() + ",'3501')";
            qrot->exec(sq);

            //sq = "update pha_com_storage set upload_no = "+bch_code1+" where group_code = '";
            sq = "update pha_com_stockinfo set upload_no = "+bch_code1+" where drug_code = '";
            sq += inpu1["fixmedins_hilist_id"].toString() +"'";

            qrot->exec(sq);
        }
        else
        {
            if(ui->rb_err_return->isChecked())
            {
                break;
            }
        }

        if(ui->ckb_no3502->isChecked())
        {
            //特殊操作，不进行库存变更
            continue;
        }

        inpu2.insert("med_list_codg", qro->value(0).toString());//医疗目录编码	字符型	50
        inpu2.insert("fixmedins_hilist_id", qro->value(1).toString());//定点医药机构目录编号	字符型	30
        inpu2.insert("fixmedins_hilist_name", qro->value(2).toString());//定点医药机构目录名称	字符型	200
        //inpu2.insert("fixmedins_bchno", qro->value(7).toString());//定点医药机构批次流水号	字符型	30
        inpu2.insert("fixmedins_bchno", bch_code2);//定点医药机构批次流水号	字符型	30
        inpu2.insert("rx_flag", qro->value(3).toString());//处方药标志	字符型	3
        inpu2.insert("cnt", qro->value(5).toString());//变更数量	数值型	16,2
        inpu2.insert("pric", qro->value(10).toString());//单价	数值型	16,6
        inpu2.insert("inv_chg_opter_name", pub::usr_code);//库存变更经办人姓名	字符型	50
        inpu2.insert("inv_chg_type", "108");//库存变更类型	字符型	108 , 盘点
        inpu2.insert("inv_chg_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));//库存变更时间
        inpu2.insert("memo", "");//备注	字符型	500
        QString split = qro->value("split_type").toString();
        if(split == "0")
        {
            inpu2.insert("trdn_flag", "1");//	拆零标志	字符型	2
        }
        else
        {
            inpu2.insert("trdn_flag", "0");//	拆零标志	字符型	2
        }


        in2.insert("invinfo",inpu2);

        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 3502 : "<<QJsonDocument(in2).toJson() << "\r\n";

        if(call_noRet("3502",in2))
        {
            ui->ptOut->appendPlainText("  " + qro->value(2).toString() + " - 3502 已传送。");
            //ui->ptOut->scroll(0,20);
            sq = "insert into pha_com_sto_upload "
                 "(fixmedins_bchno,relate_bchno,oper_date,drug_code,drug_name,count,type) "
                 "values(";
            sq += "'" + bch_code2 + "','" + bch_code1 + "', sysdate, '";
            sq += inpu2["fixmedins_hilist_id"].toString() + "','";
            sq += inpu2["fixmedins_hilist_name"].toString() + "',";
            sq += inpu2["cnt"].toString() + ",'3502')";
            qrot->exec(sq);
        }
        else
        {
            if(ui->rb_err_return->isChecked())
            {
                break;
            }
        }
    }
    ui->ptOut->appendPlainText("\n共处理数据 " + QString::number(recCount) + " 条。");

    logFile->flush();
    logFile->close();

}

void Form_qlsjsc::on_pushButton_clicked()
{
    if(!ui->cb3501->isChecked() && !ui->cb3503->isChecked() && !ui->cb3504->isChecked() &&
            !ui->cb3505->isChecked() && !ui->cb3506->isChecked() )
    {
        QMessageBox::information(this,"注意","未选定有效上传范围！");
        return;
    }

    ui->pbUpload->setEnabled(false);
    qApp->processEvents();

    if(ui->cb3501->isChecked())//盘存
    {
        search3501();//盘存
    }

    if(ui->cb3503->isChecked())
    {
        search0304("3503", "01");   //一般入库
    }
    if(ui->cb3504->isChecked())
    {
        search0304("3504", "06");   //入库退库
    }
    if(ui->cb3505->isChecked())
    {
        search0506("3505","M1");   //发药
    }
    if(ui->cb3506->isChecked())
    {
        search0506("3506","M2");   //退药
    }

    ui->pbUpload->setEnabled(true);
}

void Form_qlsjsc::search0304(QString busi, QString intype)
{
    QString dept_type;

    sq = "select a.med_list_codg, a.drug_code, a.trade_name," // 0 - 2
            " a.company_code, a.manu_date,　d.producer_code,"  // 3 - 5
            " d.approve_info, a.batch_no, a.manu_date, "
            "a.valid_date, a.in_num,'1',"  //6 - 11
            " to_char(a.apply_date,'yyyy-mm-dd hh24:mi:ss'), a.oper_code, " //12 - 13
            " a.in_bill_code, to_char(a.retail_price/a.pack_qty,'fm99999.999999'), "//14 - 15
            " a.mark, a.invoice_no, a.group_code, a.drug_dept_code, d.split_type"//16 - 20
            " from pha_com_input a,  pha_com_baseinfo d "
            " where ";

    sq += " a.oper_date between to_date('"
            + ui->deStart->date().toString("yyyy-MM-dd")
            + "','yyyy-mm-dd') and to_date('"
            + ui->deEnd->date().toString("yyyy-MM-dd")
            + " 23:59:59','yyyy-mm-dd hh24:mi:ss')";

    sq += " and a.manu_date is not null and in_type = '" + intype ;
    sq += "' and a.drug_dept_code "
          " in(select dept_code from com_department where dept_type = 'PI') ";
    sq += " and a.drug_code = d.drug_code";
    sq += " and (a.upload_no = 0 or a.upload_no is null )";


    qDebug()<<"提取入库，退库数据："<<sq;

    int recCount = 0;

    QString intp;
    if(intype == "01")
    {
        intp = "入库" ;
    }
    else
    {
        intp = "退库" ;
    }


    ui->ptOut->appendPlainText( "检索 "+ intp + "\n");

    qro->exec(sq);

    while(qro->next())
    {
        recCount ++ ;
        ui->ptOut->appendPlainText(
                    qro->value(12).toString()
                    +" / "
                    +qro->value("drug_code").toString()
                    +" / "
                    +qro->value("trade_name").toString()
                    +" / "
                    +qro->value("in_num").toString()
                    );
    }
    ui->ptOut->appendPlainText(intp + " 可上传数据 " + QString::number(recCount) + " 条。\n");

}

void Form_qlsjsc::search0506(QString busi, QString outtype)
{

    sq = "select b.med_list_codg, a.drug_code,  a.trade_name, " //0-2
            " h.doct_code, a.oper_code, " //医师姓名，药师姓名 待生成 json 时查询。 3-4
            " a.oper_code, '-', h.paykind_code, 'c.setl_id', 'c.mdtrt_id', a.batch_no,"// 5 - 10
            " CASE WHEN a.manu_date is null THEN"
            "     (select to_char(manu_date,'yyyy-mm-dd') "
            "     from pha_com_storage e "
            "     where rownum = 1 and e.drug_code = a.drug_code "
            "     and e.group_code = a.group_code and a.batch_no = e.batch_no) "
            "     ELSE to_char(a.manu_date,'yyyy-mm-dd') END," //11
            " to_char(a.valid_date,'yyyy-mm-dd'), '1', '0', h.invoice_no, a.out_num," //12-16
            " to_char(a.apply_date, 'yyyy-mm-dd hh24:mi:ss'), a.oper_code, " //17-18
            "  a.out_bill_code, to_char(a.retail_price/a.pack_qty,'fm99999.999999'), "//19-20
            " a.get_person, a.group_code, a.recipe_no, base.split_type, "//21-24
            " to_char(a.oper_date,'yyyy-mm-dd hh24:mi:ss'),a.get_person" //25-26
            " from "
            " pha_com_output a , "
            " fin_com_compare b , "
            " PHA_STO_RECIPE h ,"
            " pha_com_baseinfo base "
            " where ";


    sq += " a.oper_date between to_date('"
            + ui->deStart->date().toString("yyyy-MM-dd")
            + "','yyyy-mm-dd') and to_date('"
            + ui->deEnd->date().toString("yyyy-MM-dd")
            + " 23:59:59','yyyy-mm-dd hh24:mi:ss')" ;
    //" and b.center_name like '%"
    //+ ui->leName->text().trimmed() + "%'" ;

    sq += " and out_type = '" + outtype + "' ";
    sq += " and b.fixmedins_hilist_id = a.drug_code "
          " and base.drug_code = a.drug_code "
          " and h.recipe_no = a.recipe_no ";

    sq += " and (a.upload_no = 0 or a.upload_no is null )";


    qDebug()<<busi<<" 提取数据："<<sq;

    QString ottp;
    if(outtype == "M2")
    {
        ottp = "退费处方" ;
    }
    else
    {
        ottp = "收费处方" ;
    }

    int recCount = 0 ;

    ui->ptOut->appendPlainText( "检索 "+ ottp + "\n");

    qro->exec(sq);

    ui->ptOut->appendPlainText("时间  门诊号 处方号 药品编码    药品名称    数量");
    while(qro->next())
    {
        recCount ++ ;
        ui->ptOut->appendPlainText(
                    qro->value(25).toString()
                    +" / "
                    +qro->value("get_person").toString()
                    +" / "
                    +qro->value("recipe_no").toString()
                    +" / "
                    +qro->value("drug_code").toString()
                    +" / "
                    +qro->value("trade_name").toString()
                    +" / "
                    +qro->value("out_num").toString()
                    );
    }
    ui->ptOut->appendPlainText(ottp + " 可上传数据 " + QString::number(recCount) + " 条。\n");
}

void Form_qlsjsc::search3501()
{
    //提取库存非零且医保对照过的数据

    sq = "select b.med_list_codg, max(a.drug_code), "
         "max(b.center_name), '1',sysdate, sum(a.store_sum), ";
    sq += "'batch_no', 'group_code',";
    sq += " sysdate + 365 , sysdate - 180, "
          "max(to_char(a.retail_price / a.pack_qty,'fm999999.999999')),"
          " max(c.split_type) ";
    sq += " from pha_com_stockinfo a, fin_com_compare b , pha_com_baseinfo c";
    sq +=" where b.his_name like '%" + ui->leName->text().trimmed()+"%'";
    sq += "  and a.drug_code = b.fixmedins_hilist_id "
          " and a.drug_code = c.drug_code "; //and a.store_sum > 0

    if(!ui->rbStoreAll->isChecked())
    {
        sq += " and (a.upload_no = 0 or a.upload_no is null) ";
    }

    sq += " group by b.med_list_codg";

    qDebug()<<"提取库存非零且医保对照过的数据,3501 : "<<sq;

    int recCount = 0;

    ui->ptOut->appendPlainText("\n检索盘存数据 \n");

    qro->exec(sq);

    while(qro->next())
    {
        recCount ++ ;
        ui->ptOut->appendPlainText(qro->value(2).toString() );
    }
    ui->ptOut->appendPlainText("\n3501 可上传数据 " + QString::number(recCount) + " 条。\n");

}
